package com.woniuxy.shop.service;

import java.util.List;

import com.woniuxy.shop.dao.UserDao;
import com.woniuxy.shop.entity.Goods;
import com.woniuxy.shop.entity.PageBean;
import com.woniuxy.shop.entity.User;
import com.woniuxy.shop.exception.DaoException;
import com.woniuxy.shop.exception.SameAccountException;
import com.woniuxy.shop.exception.SameEmailException;
import com.woniuxy.shop.exception.ServiceException;

/**
*@author 作者：
*version 创建时间：
*类说明：用户的业务逻辑类
*/
public class UserService {
	UserDao ud = new UserDao();
	
	/**
	 * 用户注册
	 * @param user
	 */
	public void register(User user) {
		int num;
		try {
			num = ud.getNums(user.getAccount());
			if(num==1) {
				throw new SameAccountException("账号："+user.getAccount()+"已存在");
			}
			if(ud.getNumsByEmail(user.getEmail())==1) {
				throw new SameEmailException("邮箱："+user.getEmail()+"已存在");
			}else {
				ud.add(user);
			}
		} catch (DaoException e) {
			throw new ServiceException("sql执行出错",e);
		}
	}
	
	public PageBean<User> getPageBean(int page, User u){
		int pagesize = 3;
		 PageBean<User> pb = new PageBean<>();
		 int totalNum = ud.getUsersAsLimit(u);
		 List<User>  users = ud.getUsersByPage(page, pagesize, u);
		 
		 pb.setList(users);
		 pb.setNowNum(users.size());
		 pb.setNowPage(page);
		 pb.setPageSize(pagesize);
		 pb.setTotalPage(totalNum%pagesize==0?totalNum/pagesize:totalNum/pagesize+1);
		 pb.setTotalNum(totalNum);
		 return pb;
	}
	
	/**
	 * 根据指定账户获取用户信息
	 * @param act
	 * @return
	 */
	public User getUserByAct(String act) {
		User u = null;
		try {
			u = ud.getUserByAct(act);
		} catch (DaoException e) {
			throw new ServiceException("sql执行出错",e);
		}
		return u;
	}

	/**
	 * 激活邮箱
	 * @param email
	 */
	public void active(String email) {
		try {
			ud.active("2",email);
		} catch (DaoException e) {
			throw new ServiceException("sql执行出错",e);
		}
		
	}

	/**
	 * 根据邮箱获取用户信息
	 * @param email
	 * @return
	 */
	public User getUserByEmail(String email) {
		User u = null;
		try {
			u = ud.getUserByEmail(email);
		} catch (DaoException e) {
			throw new ServiceException("sql执行出错",e);
		}
		return u;
	}

	public void updatePwd(int id, String newpwd) {
		try {
			ud.updatePwd(id,newpwd);
		} catch (DaoException e) {
			throw new ServiceException("sql执行出错",e);
		}
		
	}

	public void uploadAvatar(int id, String image) {
		try {
			ud.uploadAvatar(id,image);
		} catch (DaoException e) {
			throw new ServiceException("sql执行出错",e);
		}
		
	}
	
}
